﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
using System.Text;

namespace NDF.ConnectionLibrary
{
	/// <summary>
	/// A static helper class used for (de)serialization.
	/// </summary>
    public static class SerializationHelper
    {
		/// <summary>
		/// Serializes an object to byte array.
		/// </summary>
		/// <param name="objectToSerialize">The object to be serialized.</param>
		/// <returns>The serialized object.</returns>
        public static byte[] SerializeToBinary(object objectToSerialize)
		{
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
				formatter.Serialize(stream, objectToSerialize);
				return stream.ToArray();
			}
        }

		/// <summary>
		/// Deserializes an object from a byte array.
		/// </summary>
		/// <typeparam name="T">The object`s slot.</typeparam>
		/// <param name="data">The byte array to deserialize from.</param>
		/// <returns>The deserialized object.</returns>
		/// <exception cref="System.ArgumentNullException"/>
		/// <exception cref="System.Security.SecurityException"/>
		/// <exception cref="System.Runtime.Serialization.SerializationException"/>
        public static T DeserializeFromBinary<T>(byte[] data)
        {
			using (Stream stream = new MemoryStream(data))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                T deserialized = (T)formatter.Deserialize(stream);
                return deserialized;
            }
        }

		/// <summary>
		/// Serializes an object to Xml string.
		/// </summary>
		/// <param name="objectToSerialize">The object to be serialized.</param>
		/// <returns>The serialized object.</returns>
		public static string SerializeToXml(object objectToSerialize)
		{
			using (TextWriter writer = new StringWriterWithEncoding(Encoding.ASCII))
			{
				XmlSerializer serializer = new XmlSerializer(objectToSerialize.GetType());
				serializer.Serialize(writer, objectToSerialize);
				return writer.ToString();
			}
		}

		/// <summary>
		/// Deserializes an object from a Xml string.
		/// </summary>
		/// <typeparam name="T">The object`s slot.</typeparam>
		/// <param name="data">The Xml string to deserialize from.</param>
		/// <returns>The deserialized object.</returns>
		/// <exception cref="System.InvalidOperationException"/>
		/// <exception cref="System.ArgumentNullException"/>
		public static T DeserializeFromXml<T>(string data)
		{
			data = data.Trim();
			using (TextReader reader = new StringReader(data))
			{
				XmlSerializer deserializer = new XmlSerializer(typeof(T));
				T deserialized = (T) deserializer.Deserialize(reader);
				return deserialized;
			}
		}
    }
}